//
//  YpViewController.m
//  KIASupervisory
//
//  Created by apple on 15/7/19.
//  Copyright (c) 2015年 MyCompany. All rights reserved.
//

#import "WeixListViewController.h"
#import "WeixViewController.h"
#import "MainViewController.h"
#import "BaoxViewController.h"
#import "MJRefresh.h"

@interface WeixListViewController ()

@property (nonatomic, strong) NSMutableArray *weixiuList;
@property (nonatomic, strong) UIButton *back;
@property (nonatomic, strong) NetworkManager *networkManager;
@property (nonatomic, strong) MBProgressHUD *HUD;
@property (retain, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, assign) NSInteger selectedRow;

@end

@implementation WeixListViewController

@synthesize dataList = _dataList;
@synthesize showData = _showData;

- (void)viewDidLoad
{
    [self.navigationController setNavigationBarHidden:YES];
    [super viewDidLoad];
    
    self.weixiuList = [NSMutableArray array];
    _tableView.frame  = CGRectMake(0, 70, self.view.frame.size.width, self.view.frame.size.height-70);
    [[self view] addSubview:[self tableView]];
    self.networkManager = [[NetworkManager alloc] init];
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.HUD];
    self.HUD.delegate = self;
    [self setupRefresh];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self performSelector:@selector(getWzList) withObject:nil afterDelay:0.3];

}

//改变行的高度

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 65;
}

/**
 为了保证内部不泄露，在dealloc中释放占用的内存
 */
- (void)dealloc
{
    NSLog(@"MJTableViewController--dealloc---");
}


/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView headerBeginRefreshing];
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"智慧管家正在帮你刷新中...";
    
}


#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 1秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
    });
}

- (IBAction)backToPre:(id)sender {
[self.navigationController popViewControllerAnimated:YES];    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];     // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [self getWzList];
    [super viewWillAppear:animated];
   
}

- (void)refreshViewByReloadData {
    [self getWzList];
}

- (void)getWzList { 
    
    [self.weixiuList removeAllObjects];
    
    
    // UserInfo *user = [UserInfo instance];
    if (self.networkManager == nil) {
        self.networkManager = [[NetworkManager alloc] init];
    }
    
    UserInfo *user = [UserInfo instance];
   
    NSLog(@"@@@@@@xiaoqu_id====%@",[user.info objectForKey:@"xiaoqu_id"]);
    NSString *xiaoqu_id = @"8";
    
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           xiaoqu_id,@"xiaoqu_id",nil];
    [self.networkManager requestWithMethod:weixiuList parameter:param delegate:self];
    [self.HUD show:YES];
    
    //    }
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    //[self endRefresh];
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.weixiuList count];
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    //[self endRefresh];
    //self.isRefreshing = NO;
    
    if (methodId == weixiuList) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * result = [data objectForKeyOrNil:@"result"];
            NSLog(@"@@@@@@@@@@@@@@@@11111%@",result);
            if([result isEqualToString:@"000"]){
                
                //NSArray *componentData2 = data[@"wenzhangList"];
                [self.weixiuList removeAllObjects];
                
                NSArray *results = [data objectForKeyOrNil:@"weixiuList"];
                NSLog(@"@@@@@@@@@@@@@@@@11111%@",results);
                if (![results isKindOfClass:[NSNull class]] && [results count] > 0) {
                    [self.weixiuList  addObjectsFromArray:results];
                }
                
                
                [self.tableView reloadData];
            } else if([result isEqualToString:@"001"]){
                NSString * resultinfo = [data objectForKeyOrNil:@"resultinfo"];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:[resultinfo stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
                
            }
        }
        
    }
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    //[self.HUD hide:YES];
    //[self endRefresh];
    //self.isRefreshing = NO;
    
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    
    NSInteger code = error.code;
    if (code != 1) {
        if ([msg length] == 0) {
            msg = @"数据获取失败，请稍后重试";
        }
    }
    
    if ([msg length] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *WeixListCell = @"WeixListCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                             WeixListCell];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:WeixListCell];
    }
    if (self.weixiuList != nil && self.weixiuList.count >0) {
        NSUInteger row = [indexPath row];
        NSLog(@"@@@@===%@",[self.weixiuList objectAtIndex:row]);
        UILabel *titleLbl = (UILabel *)[cell.contentView viewWithTag:101];
        UILabel *baoxDateLbl = (UILabel *)[cell.contentView viewWithTag:102];
        UILabel *idLbl = (UILabel *)[cell.contentView viewWithTag:103];
        UIImageView *pingjiaImg = (UIImageView *)[cell.contentView viewWithTag:104];
        UIImageView *tupianImg = (UIImageView *)[cell.contentView viewWithTag:105];
        UIImageView *stateImg = (UIImageView *)[cell.contentView viewWithTag:106];
        UILabel *stateLbl = (UILabel *)[cell.contentView viewWithTag:107];
        //UILabel *weizLbl = (UILabel *)[cell.contentView viewWithTag:108];
        NSDictionary* dic = [self.weixiuList objectAtIndex:row];
//        NSLog(@"the title is %@",[dic objectForKey:@"title"]);
//        NSLog(@"the baoxDate is %@",[dic objectForKey:@"baoxDate"]);
//        NSLog(@"the hasPj is %@",[dic objectForKey:@"hasPj"]);
        NSLog(@"the hasImages is %@",[dic objectForKey:@"hasImages"]);
//        NSLog(@"the state is %@",[dic objectForKey:@"state"]);
        
        idLbl.text = [NSString stringWithFormat:@"%@",[dic objectForKey:@"id"]];
        NSString *unicodeStr = [[dic objectForKey:@"title"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        titleLbl.text = unicodeStr;
        baoxDateLbl.text = [dic objectForKey:@"baoxDate"];
        //weizLbl.text = [dic objectForKey:@"baoxRenName"];

        if([dic objectForKey:@"pics"] != nil && ![[dic objectForKey:@"pics"] isEqualToString:@""]){
            tupianImg.hidden = NO;
        } else{
            tupianImg.hidden = YES;

        }
//        if(![[dic objectForKey:@"hasImages"] boolValue]){
//            tupianImg.hidden = YES;
//        }
        if([[dic objectForKey:@"state"] integerValue] == 1 ){
            stateLbl.text = @"已提交";
            [stateImg setImage:[UIImage imageNamed:@"weix_list_ing.png"]];
        } else if([[dic objectForKey:@"state"] integerValue] == 2){
            stateLbl.text = @"受理中";
            [stateImg setImage:[UIImage imageNamed:@"weix_list_bxing.png"]];
        } else if([[dic objectForKey:@"state"] integerValue]== 3){
            if([[dic objectForKey:@"shenhState"] integerValue]== 0){
                stateLbl.text = @"返修";
                [stateImg setImage:[UIImage imageNamed:@"weix_list_bxing.png"]];
            } else {
                stateLbl.text = @"已维修";
                [stateImg setImage:[UIImage imageNamed:@"weix_list_wcing.png"]];
            }
            
        } else if([[dic objectForKey:@"state"] integerValue]== 4){
            stateLbl.text = @"待审核";
            [stateImg setImage:[UIImage imageNamed:@"weix_list_bxing.png"]];
        }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSInteger row = indexPath.row;
    self.selectedRow = row;
    
    if ([self.weixiuList count] > row) {
        if ([self.weixiuList count] > row) {
            WeixViewController *reportVC = (WeixViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"WeixViewController"];
            NSDictionary *wzInfo = [self.weixiuList objectAtIndex:row];
            reportVC.wzInfo = wzInfo;
            [self.navigationController pushViewController:reportVC animated:YES];
             
        }
        
    }
    
}


@end

